import { useState, useEffect, useCallback } from 'react'
import { WhiteSpace, WingBlank, Card, Button, Flex } from 'antd-mobile'
import { message, Spin, Empty } from 'antd'
import router from 'umi/router'

import useMap from '@/components/map'
import api from '@/services'
import { mapQuery } from '@/utils'
import styles from './index.scss'

const { SBRegdate, SBBranchs, SBOrder } = api
export default () => {
  let timer = ''
  const itemId = Number(mapQuery().itemId) // 上一页选择的事项
  const openId = localStorage.getItem('openId')
  const [loading, setLoading] = useState(false) // 日期加载状态
  const [spinning, setSpinning] = useState(false) // 网点列表加载状态
  const [arr, setArr] = useState([]) // 日期列表
  const [cards, setCards] = useState([]) // 网点列表
  const [regdate, setRegdate] = useState('') // 已选日期
  const [branchId, setBranchId] = useState('') // 已选网点
  const [ampm, setAmpm] = useState(null) // 已选时间段

  const onPositionClick = useCallback(({ latitude, longitude }) => { // 点击位置打开对应定位
    useMap({ latitude, longitude })
  }, [])

  const requestArr = useCallback(() => { // 获取日期列表
    const data = {
      openId,
      departmentId: 0,
      districtId: 0,
      itemId
    }
    setLoading(true)
    SBRegdate({
      sign: `${JSON.stringify(data)}$$##1234ech**`.MD5(32),
      data
    })
      .then(res => {
        console.log('获取日期清单', res)
        if (res.success) {
          setArr(res.data)
          setLoading(false)
          setRegdate(res.data[0] && res.data[0].regdate)
          requestCards(res.data[0] && res.data[0].regdate)
        } else {
          setArr([])
          message.error('无法获取日期列表')
        }
      })
  }, [itemId])

  const requestCards = regdate => { // 获取网点列表
    if (regdate) {
      const data = {
        openId,
        regdate,
        itemId
      }
      setSpinning(true)
      SBBranchs({
        sign: `${JSON.stringify(data)}$$##1234ech**`.MD5(32),
        data
      })
        .then(res => {
          console.log('网点列表', res)
          if (res.success) {
            setCards(res.data)
          }
          setSpinning(false)
        })
    }
  }

  const onDateClick = useCallback((i) => { // 日期点击回调
    clearTimeout(timer)
    timer = setTimeout(() => {
      requestCards(i.regdate)
    }, 300)
    setRegdate(i.regdate)
  }, [])

  const onAppmClick = useCallback((appm, branchId) => { // 时间点选择回调
    setBranchId(branchId)
    setAmpm(appm)
  }, [])

  const onSubmit = useCallback(() => { // 预约
    if (ampm !== 0 && !ampm) {
      message.warn('请选择预约网点')
      return
    }
    const data = {
      openId,
      regdate,
      itemId,
      branchId,
      ampm
    }
    SBOrder({ // 预约号码
      sign: `${JSON.stringify(data)}$$##1234ech**`.MD5(32),
      data
    })
      .then(res => {
        if (res.success) {
          router.push('/result')
        }
      })
  }, [openId, regdate, itemId, branchId, ampm])

  useEffect(() => {
    requestArr()
  }, [])

  return (
    <Spin spinning={loading}>
      <div className={styles.hd}>
        <div className='t-left mgl-8'>请选择你要预约的时间：</div>
        <div className={styles.dateBox}>
          {
            arr.map(i => (
              <div className={`${styles.dateCard} ${regdate === i.regdate ? styles.active : ''}`} key={JSON.stringify(i)} onClick={() => onDateClick(i)}>
                <div>{i.weekday}</div>
                <div className={styles.date}>{i.regdate}</div>
              </div>
            ))
          }
        </div>
      </div>
      <WingBlank>
        <WhiteSpace />
        <Spin spinning={spinning}>
          {
            cards.length
              ? cards.map(i => {
                let am = `上午（剩余${i.leftAm}）`
                let pm = `下午（剩余${i.leftPm}）`
                if (i.leftAm === i.totalAm) {
                  am = '上午（已满）'
                }
                if (i.leftPm === i.totalPm) {
                  pm = '下午（已满）'
                }
                return (
                  <div key={i.branchId}>
                    <WhiteSpace />
                    <Card>
                      <Card.Header
                        title={i.address}
                        extra={<a onClick={() => onPositionClick({ latitude: i.latitude, longitude: i.longitude })}>位置</a>}
                      />
                      <Card.Body>
                        <Flex>
                          <Flex.Item>
                            <div className={`${styles.ampm} ${ampm === 0 && branchId === i.branchId ? styles.active : ''}`} onClick={() => onAppmClick(0, i.branchId)}>{am}</div>
                          </Flex.Item>
                          <Flex.Item>
                            <div className={`${styles.ampm} ${ampm === 1 && branchId === i.branchId ? styles.active : ''}`} onClick={() => onAppmClick(1, i.branchId)}>{pm}</div>
                          </Flex.Item>
                        </Flex>
                      </Card.Body>
                    </Card>
                  </div>
                )
              })
              : <Empty description='暂无网点信息' />
          }
        </Spin>
        <WhiteSpace />
        <Button type='primary' onClick={onSubmit}>预约</Button>
      </WingBlank>
    </Spin>
  )
}